<template>
  <el-container>
    <el-main>
      <el-form ref="updateForm" size="small" :model="parmsValue.update" label-width="160px" :rules="form.rules" class="middle-form-page">
        <el-row>
          <el-col :span="12">
            <el-form-item prop="fee_adtype" label="费用类型">
              <el-select v-model="parmsValue.update.fee_adtype" :clearable="true" :disabled="!addMod" @change="loadInvestFeeType">
                <el-option v-for="(value,key,index) in dict.fee_adtype" :key="index" :value="index+1" :label="value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="plan_code" label="方案代码">
              <el-input v-model="parmsValue.update.plan_code" :clearable="true" :disabled="!addMod" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="plan_name" label="方案名称">
              <el-input v-model="parmsValue.update.plan_name" :clearable="true" :disabled="detailMod" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item prop="invest_fee_type" label="费用类型">
              <el-checkbox-group v-model="parmsValue.update.invest_fee_type" :disabled="detailMod" @change="changeInvestFeeType">
                <el-checkbox v-for="(item,index) in parmsValue.update.invest_fee_type_option" :key="index" :label="item.itemval" />
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="form-line" />
      </el-form>
      <template v-show="parmsValue.feePage.length > 0">
        <fee-page v-for="(item,index) in parmsValue.feePage" :key="index" :ref="item.id" :edit-mod="editMod" :parms-value="item" class="fee-page" :dict="dict" />
      </template>
      <el-row class="middle-form">
        <el-button v-if="addMod" type="success" size="small" @click="saveFeeInfo">提交</el-button>
        <el-button v-if="updateMod" type="success" size="small" @click="updateFeeInfo">提交</el-button>
        <el-button type="info" size="small" @click="cancel">关闭</el-button>
      </el-row>
    </el-main>
    <!--列表结束-->
  </el-container>
</template>

<script>
  import { formItems } from '@/utils/formItems'
  import * as kk from '@/utils/k-utils'
  import request from '@/utils/request'
  import FeePage from '@/views/page/M8/fee/feeManage/feePage'
  import axios from 'axios'

  export default {
    components: { FeePage },
    props: {
      editMod: { type: String, default: 'detail' }, feeAdtype: { type: Number, default: 1 },
      planCode: { type: String, default: '' }, planName: { type: String, default: '' }, id: { type: Number, default: 1 }
    },
    data() {
      return {
        dict: {
          fee_adtype: {},
          t8_billing_number: {},
          t8_pay_fee: {},
          t8_invest_fee_model: {},
          t8_intr_base: {},
          t8_next_workday: {}
        },
        form: {
          rules: {
            plan_code: [{ required: true, message: '费用代码必填', trigger: 'change' }],
            fee_adtype: [{ required: true, message: '费用类型必选', trigger: 'change' }],
            plan_name: [{ required: true, message: '方案名称必填', trigger: 'change' }],
            invest_fee_type: [{ required: true, message: '费用类型必选', trigger: 'change' }]
          }
        },
        parmsValue: {
          // 增删改字段值
          update: {
            // checkbox类型需现有vue监听属性，否则不显示
            id: '', invest_fee_type: [], invest_fee_type_option: [], plan_code: '', plan_name: '', fee_adtype: '', billing_number: ''
          },
          feePage: [],
          // 用来删除全部费用信息用的
          originFeePlanId: []
        }
      }
    },
    computed: {
      updateMod() {
        return this.editMod === 'update'
      },
      detailMod() {
        return this.editMod === 'detail'
      },
      addMod() {
        return this.editMod === 'add'
      }
    },
    // 生命周期开始
    activated() {
      if (this.planCode || this.addMod) {
        this.init()
      }
    },
    // 生命周期结束
    methods: {
      /**
       * 新增费用方案
       */
      saveFeeInfo() {
        // 校验子组件表单
        this.parmsValue.feePage.forEach(page => {
          this.$refs[page.id][0].$refs['updateForm'].validate(valid => {
            // 校验父组件表单
            this.$refs['updateForm'].validate(valid => {
              if (valid) {
                this.saveFeePlan().then(resp => {
                  if (resp.success) {
                    kk.k_close_self_page()
                    this.$message.success('新增费用方案成功')
                  }
                })
              }
            })
          })
        })
      },
      /**
       * 更新费用方案
       */
      updateFeeInfo() {
        this.$refs['updateForm'].validate(valid => {
          // 先删除原来的，再重新插入
          this.delFeePlanByIds().then(resp => {
            if (resp.success) {
              this.saveFeePlan().then(resp => {
                if (resp.success) {
                  kk.k_close_self_page()
                  this.$message.success('更新费用方案成功')
                }
              }
              )
            }
          })
        })
      },
      /**
       * 先删除原来的费用方案，返回底层Promise，供上层调用
       */
      delFeePlanByIds() {
        if (this.parmsValue.originFeePlanId.length <= 0) {
          this.$message.error('数据ID为空')
          return
        }

        const feePlanIds = this.parmsValue.originFeePlanId.join(',')
        return kk.k_update_exeid(formItems.FEE, 'delFeePlanByIds', {
          feePlanIds: feePlanIds
        })
      },
      /**
       * 新增新的费用方案，返回底层Promise，供上层调用
       */
      saveFeePlan() {
        const data = new FormData()
        data.append('fee_adtype', this.parmsValue.update.fee_adtype)
        data.append('show_type', this.parmsValue.update.fee_adtype === 1 ? 1 : 2)
        data.append('plan_code', this.parmsValue.update.plan_code)
        data.append('plan_name', this.parmsValue.update.plan_name)

        for (const page of this.parmsValue.feePage) {
          delete page.plan_code
          delete page.fee_adtype
          delete page.plan_name
          for (const key of Object.keys(page)) {
            data.append(key, page[key])
          }
        }

        return request.post(
          formItems.FEE + '/fee/saveFeePlan.json',
          data, {
            headers: { 'Content-Type': 'application/x-www-form-urlencoded;' }
          }
        )
      },

      cancel() {
        switch (this.editMod) {
        case 'update':
          kk.k_close_self_page()
          break
        case 'add':
          kk.k_close_self_page()
          break
        case 'detail':
        default:
          kk.k_close_self_page()
        }
      },

      resetFields(form) {
        this.$refs[form].resetFields()
        this.parmsValue.feePage = []
      },

      init() {
        // 路由赋值结束
        const dictReq = []
        const dicts = ['t8_billing_number', 't8_pay_fee', 't8_invest_fee_model', 't8_intr_base', 't8_next_workday', 't8_fee_adtype']
        dicts.forEach(key => dictReq.push(request({ url: 'system/base/dict/' + key + '.json', method: 'post', loading: true })))
        axios.all(dictReq).then(axios.spread((billing_number, pay_fee, invest_fee_model, intr_base, next_workday, fee_adtype) => {
          this.dict['t8_billing_number'] = billing_number
          this.dict['t8_pay_fee'] = pay_fee
          this.dict['t8_invest_fee_model'] = invest_fee_model
          this.dict['t8_intr_base'] = intr_base
          this.dict['t8_next_workday'] = next_workday
          this.dict['fee_adtype'] = fee_adtype

          if (!this.addMod) {
            this.loadData(this.feeAdtype)
          }
        }))
      },

      loadFeePage() {
        this.parmsValue.feePage = []
        this.parmsValue.update.invest_fee_type = []
        kk.k_load_exeid(formItems.FEE, 'M8QueryFeePlanForUpdate', {
          fee_adtype: this.parmsValue.update.fee_adtype,
          plan_code: this.parmsValue.update.plan_code,
          plan_name: this.parmsValue.update.plan_name
        }).then(resp => {
          if (resp.results > 0) {
            for (const eachFee of resp.rows) {
              const each = this.parmsValue.update.invest_fee_type_option.find(temp => temp.itemkey === eachFee.t8_fee_info_id)
              if (each) {
                this.parmsValue.update.invest_fee_type.push(each.itemval)
                eachFee.fee_name = each.itemval
                this.parmsValue.feePage.push(eachFee)
                this.parmsValue.originFeePlanId.push(eachFee.id)
              }
            }
          }
        })
      },

      loadData(feeAdType) {
        kk.k_load_exeid(formItems.FEE, 'M8loadfees', { fee_adtype: feeAdType }).then(resp => {
          if (resp.results > 0) {
            // this.resetFields('updateForm')
            this.parmsValue.update.invest_fee_type_option = resp.rows
            // 保持同步请求
            if (!this.addMod) {
              // 参数赋值开始，由于这些参数可修改，因此需要data内变量承担
              this.parmsValue.update.fee_adtype = this.feeAdtype
              this.parmsValue.update.plan_code = this.planCode
              this.parmsValue.update.plan_name = this.planName
              this.loadFeePage()
            }
            // 保持同步请求
          }
        })
      },
      /**
       * 为避免新增或减少导致原先初始化时有的数据被清空，这里新增或减少分开进行
       * @param params
       */
      changeInvestFeeType(params) {
        if (params.length <= 0) {
          this.parmsValue.feePage = []
          return
        }

        // 处理新增
        for (const feeName of params) {
          if (this.parmsValue.feePage.findIndex(page => page.fee_name === feeName) === -1) {
            const feeInfoId = this.parmsValue.update.invest_fee_type_option.find(item => item.itemval === feeName)
            const newFee = { fee_name: feeName, t8_fee_info_id: feeInfoId.itemkey }
            // 初始化共同参数开始
            newFee.billing_number = ''
            newFee.fee_base = ''
            newFee.collect_fee_cycle = ''
            newFee.fee_model = ''
            newFee.rates_value = '0'
            newFee.cost_value = '0'
            newFee.cost_value_down = '0'
            newFee.cost_value_up = '0'
            newFee.firstdate = ''
            // 初始化共同参数结束
            this.parmsValue.feePage.push(newFee)
          }
        }

        // 处理减少
        for (let i = 0; i < this.parmsValue.feePage.length; i++) {
          if (params.findIndex(feeName => feeName === this.parmsValue.feePage[i].fee_name) === -1) {
            this.parmsValue.feePage = this.parmsValue.feePage.slice(0, i).concat(this.parmsValue.feePage.slice(i + 1))
          }
        }
      },

      /**
       * 当新增费用方案时，需要监听并加载可选费用类型
       * @param params
       */
      loadInvestFeeType(params) {
        this.loadData(params)
      }
    }
  }
</script>
